package vn.vfriends.games.bean;

import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.games.jpa.entity.Game;
import vn.vfriends.games.service.GameService;
import vn.vfriends.id.ws.User;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@ConversationScoped
public class GameBean implements Serializable {
    private final Logger logger = LoggerFactory.getLogger(GameBean.class);
    
    @Inject private GameService gameService;
    @Inject private Conversation conversation;
    private Game[] selectedGames;
    private Game game;
    private List<Game> gameList;
    
    private long gameId;
    
    @PostConstruct
    public void init(){
        gameList = gameService.findGames();
    }

    public long getGameId() {
        return gameId;
    }

    public void setGameId(long gameId) {
        this.gameId = gameId;
    }

    public List<Game> getGameList() {
        return gameList;
    }

    public List<Game> getDisplayGameList() {
        return gameService.findDisplayGames();
    }
    
    public Game[] getSelectedGames() {
        return selectedGames;
    }

    public void setSelectedGames(Game[] selectedGames) {
        this.selectedGames = selectedGames;
    }

    public Game getGame() {
        return game;
    }

    public void setGame(Game game) {
        this.game = game;
    }
    
    public Conversation getConversation() {
        return conversation;
    }
    
    public void preRenderGameDetailAction() {
        if(gameId > 0) {
            game = this.gameService.findGame(gameId);
        }
    }
    
    public void preNewAction() {
        game = new Game();
        
        if (conversation.isTransient()) {
            conversation.begin();
        }
    }
    
    public String preViewAction() {
        String outcome = "";
        FacesContext context = FacesContext.getCurrentInstance();
        
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            
            if(this.game != null) {
                outcome = "view?faces-redirect=true";
            }
            else if (this.selectedGames == null || this.selectedGames.length == 0) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn một game", ""));
            } else if (this.selectedGames.length > 1) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn chỉ một game", ""));
            } else {
                this.game = this.selectedGames[0];
                outcome = "view?faces-redirect=true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
        return outcome;
    }
    
    public String preEditAction() {
        String outcome = null;
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            
            if(this.game != null){
                outcome = "edit?faces-redirect=true";
            } else if (this.selectedGames == null || this.selectedGames.length == 0) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn một game", ""));
            } else if (this.selectedGames.length > 1) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn chỉ một game", ""));
            } else {
                this.game = this.selectedGames[0];
                outcome = "edit?faces-redirect=true";
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));

        }
        return outcome;
    }
    
    public void preDeleteAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if (conversation.isTransient()) {
                conversation.begin();
            }
            if ((this.game == null) && (this.selectedGames == null || this.selectedGames.length == 0)) {
                if (RequestContext.getCurrentInstance() != null) {
                    RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                }
                RequestContext.getCurrentInstance().addCallbackParam("invalid", true);
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Hãy chọn game", ""));
            }
        } catch (Exception e) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
    
    public String saveAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            HttpSession session = request.getSession();
            User loggedUser = (User)session.getAttribute("LOGGED_USER");
            game.setPublisher(loggedUser.getEmail());
            this.gameService.create(game);
            return "view?faces-redirect=true";
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            return null;
        }
    }
    
    public String updateAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
            HttpSession session = request.getSession();
            User loggedUser = (User)session.getAttribute("LOGGED_USER");
            game.setPublisher(loggedUser.getEmail());
            this.gameService.edit(game);
            return "view?faces-redirect=true";
        } catch (Exception ex) {
            this.logger.error(ex.getMessage(), ex);
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            return null;
        }
    }

    public String cancelAction() {
        conversation.end();
        return "list?faces-redirect=true";
    }
    
    public void deleteAction() {
        try {
            if(this.game != null) {
                this.gameService.destroy(this.game.getId());
            }
            else {
                for(Game selectedGame : selectedGames) {
                    this.gameService.destroy(selectedGame.getId());
                }
            }
            if(!conversation.isTransient()) {
                conversation.end();
            }
            FacesContext.getCurrentInstance().getExternalContext().redirect("list.jsf");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), ""));
        }
    }
}
